﻿Imports System.Linq
Imports System.Data
Imports System.Web
Imports Equipment.DataAccess

Partial Public Class AssetType
#Region "Properties"
    Private _db As EquipmentDataContext
    Public Property DBContext As EquipmentDataContext
        Get
            Return _db
        End Get
        Set(ByVal value As EquipmentDataContext)
            _db = value
        End Set
    End Property

#End Region

    Public Shared Function RetrieveAll() As IEnumerable(Of AssetType)
        Dim db As EquipmentDataContext = Database.Instance
        Return db.AssetTypes.OrderBy(Function(t) t.Description)
    End Function


    Public Shared Function GetByPrimaryKey(ByVal id As Integer) As AssetType
        Dim _dataBase As EquipmentDataContext = Database.Instance
        Dim result = From at In _dataBase.AssetTypes Where at.ID = id
        Dim assetTypeEntity As AssetType = result.FirstOrDefault()
        assetTypeEntity.DBContext = _dataBase
        Return assetTypeEntity
    End Function

    Public Shared Function IsExist(ByVal desc As String) As Boolean
        Return Database.Instance.AssetTypes.Count(Function(at) at.Description.ToUpper() = desc.ToUpper()) > 0
    End Function

    Public Shared Function Insert(ByVal description As String) As AssetType

        Dim _dataBase As EquipmentDataContext = Database.Instance
        Dim newType As New AssetType

        newType.Description = description

        _dataBase.AssetTypes.InsertOnSubmit(newType)
        Try
            _dataBase.SubmitChanges()

        Catch ex As Exception
            ' logger.Error(exception.Message + ":" + exception.StackTrace);
        End Try
        Return newType
    End Function


    Public Shared Sub Delete(ByVal id As Integer)

        Dim _dataBase As EquipmentDataContext = Database.Instance
        Dim query = From o In _dataBase.AssetTypes Where o.ID = id
        Dim deletedEntity As AssetType = query.SingleOrDefault()

        _dataBase.AssetTypes.DeleteOnSubmit(deletedEntity)

        Try
            _dataBase.SubmitChanges()

        Catch ex As Exception
            ' logger.Error(exception.Message + ":" + exception.StackTrace);
        End Try

    End Sub

    Public Sub Save()
        If Me.DBContext IsNot Nothing Then
            Dim _dataBase As EquipmentDataContext = Me.DBContext

            Try
                _dataBase.SubmitChanges()
            Catch ex As Exception
                ' logger.Error(exception.Message + ":" + exception.StackTrace);
            End Try
        End If

    End Sub

End Class
